package com.group.seckill.interceptor;

import com.alibaba.fastjson.JSON;
import com.group.common.to.UserTo;
import org.springframework.stereotype.Component;
import org.springframework.util.AntPathMatcher;
import org.springframework.web.servlet.HandlerInterceptor;
import org.springframework.web.servlet.ModelAndView;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import javax.servlet.http.HttpSession;
import java.io.PrintWriter;

/**
 * @author lins
 * @date 2021/11/15 16:21
 */
@Component
public class LoginUserInterceptor implements HandlerInterceptor {
    public static final ThreadLocal<UserTo> userTo = new ThreadLocal<>();
    @Override
    public boolean preHandle(HttpServletRequest request, HttpServletResponse response, Object handler) throws Exception {
        HttpSession session = request.getSession();
        Object attribute = session.getAttribute("loginUser");
        String uri = request.getRequestURI();
        AntPathMatcher matcher = new AntPathMatcher();
        boolean match = matcher.match("/seckill/seckill", uri);
        if (match){
            if (attribute==null){
                //没有登录
                //跳转到登录页
                response.setContentType("text/html;charset=UTF-8");
                PrintWriter writer = response.getWriter();
                writer.write("<script>\n" +
                        "      alert(\"登录后能查看,请先登录\");\n" +
                        "      location.href = \"http://localhost:88/api/admin/shopuser/login.html\";\n" +
                        "    </script>");
                return false;
            }else {
                String s = JSON.toJSONString(attribute);
                UserTo userTo = JSON.parseObject(s, UserTo.class);
                LoginUserInterceptor.userTo.set(userTo);
                return true;
            }
        }
        return true;
    }

    @Override
    public void postHandle(HttpServletRequest request, HttpServletResponse response, Object handler, ModelAndView modelAndView) throws Exception {

    }
}
